<template>
  <view class="login-container">
    <view class="login-header">
      <image class="logo" src="http://101.200.154.121:19000/teacher-manage-static/static/logo.png" mode="aspectFit"></image>
      <view class="title-container">
        <text class="title-line first">开启你的星途</text>
        <view class="second-line">
          <text v-for="(char, index) in secondLine" :key="index" class="char" :style="{ animationDelay: (0.8 + index * 0.2) + 's' }">{{char}}</text>
        </view>
      </view>
    </view>
    
    <view class="login-form">
      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <text
          class="tab-item"
          :class="{ 'active': loginType === 'password' }"
          @click="switchLoginType('password')"
        >
          密码登录
        </text>
        <text class="tab-divider">|</text>
        <text
          class="tab-item"
          :class="{ 'active': loginType === 'sms' }"
          @click="switchLoginType('sms')"
        >
          短信登录
        </text>
      </view>

      <!-- 验证码登录表单 -->
      <view v-if="loginType === 'sms'" class="form-container">
        <view class="input-group account-input-group">
          <input type="text" v-model="phone" placeholder="请输入手机号" maxlength="11" />
        </view>

        <!-- 图形验证码 -->
        <view class="input-group captcha-input-group">
          <input
            type="text"
            v-model="imageCaptcha"
            placeholder="请输入图形验证码"
            maxlength="4"
            class="captcha-input"
          />
          <view class="captcha-display">
            <captcha
              ref="captcha"
              :width="120"
              :height="48"
              :loading="captchaLoading"
              @generated="onCaptchaGenerated"
              @refresh-start="onCaptchaRefreshStart"
              @refresh-end="onCaptchaRefreshEnd"
            ></captcha>
          </view>
        </view>

        <view class="input-group code-input-group">
          <input type="text" v-model="smsCode" placeholder="请输入短信验证码" maxlength="6" />
          <button
            class="code-btn"
            :class="{ 'disabled': countdown > 0 || !canGetSmsCode }"
            @tap="getSmsCode"
          >
            {{countdown > 0 ? `${countdown}s` : '获取验证码'}}
          </button>
        </view>
      </view>

      <!-- 密码登录表单 -->
      <view v-if="loginType === 'password'" class="form-container">
        <view class="input-group account-input-group">
          <input type="text" v-model="account" placeholder="请输入手机号/账号" />
        </view>
        <view class="input-group password-input-group">
          <input
            :type="showPassword ? 'text' : 'password'"
            v-model="password"
            placeholder="请输入密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="togglePassword">
            <text class="iconfont" :class="showPassword ? 'icon-eye-open' : 'icon-eye-close'">
              {{showPassword ? '👁' : '🙈'}}
            </text>
          </view>
        </view>
      </view>

      <button class="login-btn" @click="handleLogin">
        <text class="login-btn-text">{{loginType === 'password' ? '登录' : '登录/注册'}}</text>
      </button>

<!--      &lt;!&ndash; 功能提示 &ndash;&gt;-->
<!--      <view v-if="loginType === 'sms'" class="register-tip">-->
<!--        <text class="tip-text">没有账号？验证码登录将自动注册</text>-->
<!--      </view>-->

      <!-- 密码登录时的注册提示 -->
      <view v-if="loginType === 'password'" class="register-tip">
        <text class="tip-text">还没有账号？</text>
        <text class="register-link" @click="switchToSmsLogin">短信注册</text>
      </view>
    </view>
  </view>
</template>

<script>
import { setToken, getToken } from '@/utils/request.js'
import { getCode, userApi } from '@/api/user.js'
import Captcha from '@/components/captcha/captcha.vue'

export default {
  components: {
    Captcha
  },
  data() {
    return {
      getCodeDto: {
        phone: ""
      },
      loginType: 'sms', // 登录方式：sms-短信登录（兼顾注册），password-密码登录
      phone: '',
      smsCode: '', // 短信验证码
      imageCaptcha: '', // 图形验证码
      captchaCode: '', // 当前图形验证码的正确答案
      code: '', // 兼容旧版本
      account: '', // 账号（手机号或用户名）
      password: '', // 密码
      showPassword: false, // 是否显示密码
      secondLine: '学习从这里起航'.split(''),
      countdown: 0,
      timer: null,
      isRequesting: false,
      canGetSmsCode: false, // 是否可以获取短信验证码
      captchaLoading: false // 验证码加载状态
    }
  },
  watch: {
    // 监听手机号变化
    phone() {
      this.checkCanGetSmsCode()
    },
    // 监听图形验证码变化
    imageCaptcha() {
      this.checkCanGetSmsCode()
    }
  },
  methods: {
    // 图形验证码生成回调
    onCaptchaGenerated(code) {
      this.captchaCode = code
      this.checkCanGetSmsCode()
    },

    // 验证码刷新开始
    onCaptchaRefreshStart() {
      this.captchaLoading = true
    },

    // 验证码刷新结束
    onCaptchaRefreshEnd() {
      this.captchaLoading = false
      this.imageCaptcha = '' // 清空用户输入
      this.checkCanGetSmsCode()
    },

    // 检查是否可以获取短信验证码
    checkCanGetSmsCode() {
      this.canGetSmsCode = this.validatePhone(this.phone) &&
                          this.imageCaptcha &&
                          this.imageCaptcha.toLowerCase() === this.captchaCode.toLowerCase()
    },

    // 切换登录方式
    switchLoginType(type) {
      this.loginType = type
      // 清空表单数据
      this.phone = ''
      this.smsCode = ''
      this.imageCaptcha = ''
      this.code = ''
      this.account = ''
      this.password = ''
      this.canGetSmsCode = false
      // 清除验证码倒计时
      if (this.timer) {
        clearInterval(this.timer)
        this.countdown = 0
      }
      // 刷新图形验证码
      if (type === 'sms' && this.$refs.captcha) {
        this.$nextTick(() => {
          this.$refs.captcha.refreshCaptcha()
        })
      }
    },

    // 切换密码显示状态
    togglePassword() {
      this.showPassword = !this.showPassword
    },

    // 验证手机号格式
    validatePhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },

    // 验证账号格式（手机号或用户名）
    validateAccount(account) {
      if (!account) return false
      // 如果是手机号格式，验证手机号
      if (/^1[3-9]\d{9}$/.test(account)) {
        return true
      }
      // 如果是用户名格式，验证用户名（4-20位字母数字下划线）
      if (/^[a-zA-Z0-9_]{4,20}$/.test(account)) {
        return true
      }
      return false
    },

    // 验证密码格式
    validatePassword(password) {
      // 密码长度6-20位
      return password && password.length >= 6 && password.length <= 20
    },
    
    // 获取短信验证码
    async getSmsCode() {
      if (this.isRequesting) {
        return
      }

      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }

      if (!this.validatePhone(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }

      if (!this.imageCaptcha) {
        uni.showToast({
          title: '请输入图形验证码',
          icon: 'none'
        })
        return
      }

      // 验证图形验证码
      if (this.imageCaptcha.toLowerCase() !== this.captchaCode.toLowerCase()) {
        uni.showToast({
          title: '图形验证码错误',
          icon: 'none'
        })
        // 刷新图形验证码
        this.$refs.captcha.refreshCaptcha()
        this.imageCaptcha = ''
        return
      }

      if (this.countdown > 0) {
        return
      }

      this.isRequesting = true

      try {
        uni.showLoading({
          title: '发送中...'
        })

        const requestData = {
          phone: this.phone,
          captcha: this.imageCaptcha,
          type: 'login' // 登录类型的短信验证码
        }

        const res = await userApi.getCode(requestData)

        if (res && (res.code === 200 || res.success)) {
          // 开发环境下可能会返回验证码，生产环境不会
          if (res.data && typeof res.data === 'string') {
            this.smsCode = res.data
            console.log('开发环境验证码:', res.data)
          }

          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })

          // 开始倒计时
          this.countdown = 60
          this.timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--
            } else {
              clearInterval(this.timer)
            }
          }, 1000)

          // 清空图形验证码，刷新图形验证码
          this.imageCaptcha = ''
          this.$refs.captcha.refreshCaptcha()

        } else {
          throw new Error(res.message || '获取验证码失败')
        }
      } catch (error) {
        console.error('getSmsCode error:', error)
        uni.showToast({
          title: error.message || '网络错误，请重试',
          icon: 'none',
          duration: 2000
        })
        // 刷新图形验证码
        this.$refs.captcha.refreshCaptcha()
        this.imageCaptcha = ''
      } finally {
        uni.hideLoading()
        this.isRequesting = false
      }
    },

    // 兼容旧版本的getCode方法
    async getCode() {
      return this.getSmsCode()
    },

    // 登录
    async handleLogin() {
      // 验证码登录
      if (this.loginType === 'sms') {
        return this.handleSmsLogin()
      }
      // 密码登录
      else if (this.loginType === 'password') {
        return this.handlePasswordLogin()
      }
    },

    // 验证码登录处理
    async handleSmsLogin() {
      if (!this.phone || !this.smsCode) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      if (!this.validatePhone(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({
          title: '登录中...'
        })

        const requestData = {
          phone: this.phone,
          code: this.smsCode,
          loginType: 'sms',
          autoRegister: true // 自动注册标识，如果用户不存在则自动注册
        }

        // 短信登录支持自动注册：如果手机号已注册则登录，如果未注册则自动注册后登录
        const res = await userApi.login(requestData)
        await this.handleLoginSuccess(res)
      } catch (error) {
        this.handleLoginError(error)
      } finally {
        uni.hideLoading()
      }
    },

    // 密码登录处理
    async handlePasswordLogin() {
      if (!this.account || !this.password) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      if (!this.validateAccount(this.account)) {
        uni.showToast({
          title: '账号格式不正确',
          icon: 'none'
        })
        return
      }

      if (!this.validatePassword(this.password)) {
        uni.showToast({
          title: '密码长度为6-20位',
          icon: 'none'
        })
        return
      }

      try {
        const requestData = {
          account: this.account,
          password: this.password,
          loginType: 'password'
        }

        const res = await userApi.login(requestData)
        await this.handleLoginSuccess(res)
      } catch (error) {
        this.handleLoginError(error)
      }
    },

    // 登录成功处理
    async handleLoginSuccess(res) {

      if (res && res.data) {
        // 登录成功之后的操作
        // 存储用户信息
        const userData = res.data.user || res.data
        console.log("用户信息UserData :"+JSON.stringify(userData))
        // 存储token和用户信息
        setToken(res.data.accessToken)
        uni.setStorageSync('refreshToken', res.data.refreshToken)
        uni.setStorageSync('userInfo', userData)

        // 验证token是否正确保存
        const savedToken = getToken()
        if (!savedToken) {
          console.error('Token保存失败')
          uni.showToast({
            title: '登录异常，请重试',
            icon: 'none'
          })
          return
        }

        // 更新全局登录状态
        const app = getApp()
        if (app.updateLoginStatus) {
          app.updateLoginStatus(true, userData)
        }

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        // 延迟跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
      } else {
        uni.showToast({
          title: '登录数据异常',
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 登录错误处理
    handleLoginError(error) {
      console.error('login error:', error)
      uni.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    },

    // 跳转到注册页面
    goToRegister() {
      uni.navigateTo({
        url: '/pages/signup/signup'
      })
    },

    // 切换到短信登录（用于注册）
    switchToSmsLogin() {
      this.switchLoginType('sms')
      uni.showToast({
        title: '没有账号则自动注册',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 组件销毁时清除定时器
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style>
.login-container {
  padding: 0 40rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  /* 背景图片暂不可用，后续可添加 */
  /* background-image: url('/static/login-bg.png'); */
  background-color: #f8f8f8;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20rpx;
}

.logo {
  width: 700rpx;
  height: 350rpx;
  margin-bottom: 0;
  animation: floatAnimation 3s ease-in-out infinite;
}

.title-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 0;
  margin-bottom: 40rpx;
}

.title-line {
  font-weight: bold;
  transform-origin: center;
  opacity: 0;
  animation: fadeSlide 0.8s ease forwards;
}

.first {
  font-size: 48rpx;
  color: #333;
  margin-bottom: 10rpx;
  animation-delay: 0.3s;
  background: linear-gradient(90deg, #4080FF, #1890FF);
  -webkit-background-clip: text;
  color: transparent;
  letter-spacing: 4rpx;
  opacity: 0;
  animation: fadeSlide 0.8s ease forwards;
}

.second-line {
  display: flex;
  justify-content: center;
  transform: translateX(40rpx);
}

.char {
  font-size: 36rpx;
  color: #666;
  opacity: 0;
  animation: charFadeIn 0.7s ease forwards;
  letter-spacing: 2rpx;
}

@keyframes charFadeIn {
  0% {
    opacity: 0;
    transform: translateY(40rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeSlide {
  0% {
    opacity: 0;
    transform: translateY(30rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes floatAnimation {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20rpx);
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(20rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-bottom: 0;
  margin-top: -20rpx;
}

.login-tabs {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40rpx;
  gap: 20rpx;
}

.tab-item {
  font-size: 32rpx;
  color: #999;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 10rpx 20rpx;
}

.tab-item.active {
  color: #4080FF;
  font-weight: 500;
}

.tab-divider {
  font-size: 32rpx;
  color: #ddd;
  margin: 0 10rpx;
}

.form-container {
  animation: fadeIn 0.3s ease;
}

.input-group {
  position: relative;
  margin-bottom: 30rpx;
  width: 100%;
}

.input-group input {
  width: 100%;
  height: 100rpx;
  padding: 0 100rpx 0 40rpx;
  border: 1px solid #eee;
  border-radius: 50rpx;
  font-size: 32rpx;
  background: #fff;
}

.captcha-input-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.captcha-input-group .captcha-input {
  flex: 1;
  width: auto;
  height: 100rpx;
  padding: 0 40rpx;
  border: 2rpx solid #eee;
  border-radius: 50rpx;
  font-size: 32rpx;
  background: #fff;
  transition: all 0.3s ease;
}

.captcha-input-group .captcha-input:focus {
  border-color: #4080FF;
  box-shadow: 0 0 0 6rpx rgba(64, 128, 255, 0.1);
  outline: none;
}

.captcha-input-group .captcha-input.error {
  border-color: #ff4757;
  animation: shake 0.5s ease;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-10rpx); }
  75% { transform: translateX(10rpx); }
}

.captcha-display {
  flex-shrink: 0;
  width: 240rpx;
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.code-input-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input-group input {
  flex: 1;
  width: auto;
}

.account-input-group {
  position: relative;
  display: flex;
  align-items: center;
}

.password-input-group {
  position: relative;
  display: flex;
  align-items: center;
}

.account-input-group input,
.password-input-group input {
  flex: 1;
}

.password-toggle {
  position: absolute;
  right: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #999;
  cursor: pointer;
  transition: color 0.3s;
}

.password-toggle:active {
  color: #4080FF;
}

.code-btn {
  width: 200rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 28rpx;
  color: #4080FF;
  background: rgba(64, 128, 255, 0.1);
  border: none;
  border-radius: 50rpx;
  text-align: center;
  transition: all 0.3s;
  padding: 0;
  margin: 0;
  flex-shrink: 0;
}

.code-btn:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.code-btn.disabled {
  color: #999;
  background: #f5f5f5;
}

.login-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  background: #4080FF;
  color: #fff;
  border-radius: 50rpx;
  font-size: 34rpx;
  margin-top: 50rpx;
  box-shadow: 0 8rpx 16rpx rgba(64, 128, 255, 0.2);
}

.register-tip {
  text-align: center;
  margin-top: 40rpx;
  font-size: 28rpx;
}

.tip-text {
  color: #666;
}

.register-link {
  color: #ff4757;
  font-weight: 500;
  margin-left: 8rpx;
}
</style> 